<?php

namespace App\Http\Controllers;

use DB;
use Storage;
use Session;
use Request;
use Laravel\Lumen\Routing\Controller;

require __Dir__.'/../../Library/autoload.php';
use Qiniu\Auth;

class QiniuController extends BaseController{
	public function token(){
		$bucket = 'e-invitation';
	    $accessKey = 'nxlplb4aOL9emGacuBXImfNz_2RRVA9vsS9024ke';
	    $secretKey = 'YcqTTtaZgNhxEBZAau6EEJfXMyILtkF4ddi3RjAJ';

	    $auth = new Auth($accessKey, $secretKey);

	    $upToken = $auth->uploadToken($bucket);
	    return $this->jsonResponse(false,$upToken);
	}
	
	public function makeSaveasUrl(){
		$bucket = 'e-invitation';
	    $accessKey = 'nxlplb4aOL9emGacuBXImfNz_2RRVA9vsS9024ke';
	    $secretKey = 'YcqTTtaZgNhxEBZAau6EEJfXMyILtkF4ddi3RjAJ';

		function urlsafe_base64_encode($data) {
		   $data = base64_encode($data);
		   $data = str_replace(array('+','/'),array('-','_'),$data);
		   return $data;
		}
		function getSignature($str, $key) {
	        $signature = "";
	        if (function_exists('hash_hmac')) {
	            $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
	        } else {
	            $blocksize = 64;
	            $hashfunc = 'sha1';
	            if (strlen($key) > $blocksize) {
	                $key = pack('H*', $hashfunc($key));
	            }
	            $key = str_pad($key, $blocksize, chr(0x00));
	            $ipad = str_repeat(chr(0x36), $blocksize);
	            $opad = str_repeat(chr(0x5c), $blocksize);
	            $hmac = pack(
	                    'H*', $hashfunc(
	                            ($key ^ $opad) . pack(
	                                    'H*', $hashfunc(
	                                            ($key ^ $ipad) . $str
	                                    )
	                            )
	                    )
	            );
	            $signature = base64_encode($hmac);
	        }
	        return $signature;
	    }

		$input = Request::all();
		$url = $input['url'];
		$key = $input['key'];
		$entry = $bucket.':'.$key;
		$encodedEntryURI = urlsafe_base64_encode($entry);
		$NewURL = $url. '|saveas/'.$encodedEntryURI;

		$sign = getSignature($NewURL,$secretKey);
		//$sign = base64_encode(hash_hmac("sha1", $NewURL, $secretKey, true));
		$EncodedSign = urlsafe_base64_encode($sign);
		$FinalURL = $NewURL.'/sign/'.$accessKey.':'.$EncodedSign;
		var_dump($FinalURL);exit();
	}
}